package com.songhq.netty.two;

import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class EchoClient {

	static final int port = 8080;

	public void start() throws InterruptedException {

		EventLoopGroup group = new NioEventLoopGroup();

		try {
			Bootstrap b = new Bootstrap();
			b.group(group)
					// 指定使用NIO传输通道
					.channel(NioSocketChannel.class)
					// 使用指定的端口地址
					.remoteAddress(new InetSocketAddress("127.0.0.1", port))
					// 添加一个EchoServerHandler到channel的ChannelPipeline
					.handler(new ChannelInitializer<SocketChannel>() {

						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline().addLast(new EchoClientHandler());
						}
					});
			
			ChannelFuture f = b.connect().sync();
			f.channel().closeFuture().sync();
		} finally {
			// 关闭NioEventLoopGroup，释放所有的资源
			group.shutdownGracefully().sync();
		}
	}
	public static void main(String[] args) throws InterruptedException {
		new EchoClient().start();
	}
}
